import {Injectable} from '@angular/core';
import {StorageProvider} from "@providers/storage";
import {Events} from "ionic-angular";
import {Util} from "@providers/util";
import {EnvironmentProvider} from "@providers/environment";
import {AiProvider} from "@providers/natives/ai";
import {ChatProvider} from "@providers/interface/chat";
import WebsocketHeartbeatJs from 'websocket-heartbeat-js';
import {AuthGuardProvider} from "@providers/auth-guard";

/*
  Generated class for the JlMessageProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class JlMessageProvider {

  websocket: WebSocket = null;

  constructor(private storage: StorageProvider,
              private events: Events,
              private env: EnvironmentProvider,
              private ai: AiProvider,
              private chat: ChatProvider,
              private auth: AuthGuardProvider) {

    this.events.subscribe("login", () => {
      if (this.websocket != null) this.websocket.close();
      this.checkWebsocket();
    });

    this.events.subscribe("logout", () => {
      if (this.websocket != null) {
        this.websocket.close();
      }
    });

    this.events.subscribe("websocket:sendMessage", v => this.sendMessage(v));

  }

  checkWebsocket() {
    let userInfo = this.storage.read("userInfo");
    if (!Util.isNull(userInfo) && !Util.isNull(userInfo['SessionID'])) {
      console.log("1111");
      this.createWebsocket();
    }
  }

  createWebsocket() {
    let userInfo = this.storage.read("userInfo");
    let url = this.env.env.ws_serve_url;

    //身份识别
    let sfsb: number = this.auth.isEmployee();
    if (sfsb == 0) {
      url += '/SF';
    } else if (sfsb == 1) {
      url += '/custom';
    }

    url += '/' + userInfo['SessionID'] + '/' + this.storage.read("userInfo")["GSXX01"] + '/' + userInfo['PARTYID'];

    console.log("url" + url);
    if ("WebSocket" in window) {
      this.websocket = new WebsocketHeartbeatJs({url: url});
    }

    this.websocket.onopen = () => {
      console.log("已经连接上WebSocket");
    };

    this.websocket.onmessage = (event) => {
      let data: any;
      try {
        data = JSON.parse(event.data);
        //此处在后台与前台发送消息时，都应该加上类别，以用于区分不同的消息类别
        if (data['topic'] == "chat:message") {
          this.chat.onMessage(data);
        } else {
          this.ai.text2audio(data['MESSAGE']);
        }
      } catch (e) {
        console.log(e);
      }

    };

    this.websocket.onerror = () => {
      console.log("websocket发生错误");
    };

    this.websocket.onclose = () => {
      console.log("websocket已关闭");
    }

  }


  sendMessage(v) {
    if (this.websocket) {
      try {
        v = JSON.stringify(v);
      } catch (e) {
        console.log(e);
      }
      this.websocket.send(v);
    }
  }

}
